package cn.lingyangwl.agile.msg.push.core.channel.client;

import cn.lingyangwl.agile.model.module.config.param.sms.*;
import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.*;
import cn.lingyangwl.agile.msg.push.model.rqrs.channel.*;
import cn.lingyangwl.framework.core.utils.spring.*;
import cn.lingyangwl.framework.sms.manager.*;
import cn.lingyangwl.framework.sms.manager.entity.*;
import cn.lingyangwl.framework.sms.properties.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

/**
 * 聚美短信客户端
 * @author shenguangyang
 */
@Getter
@Setter
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SmsJmMsgClient extends AbstractSmsMsgClient {
    private JMSmsManager jmSmsManager;
    private JMSmsProperties jmSmsProperties;

    @Override
    public ChannelCodeEnum channelCode() {
        return ChannelCodeEnum.SMS_JUMEI;
    }

    @Override
    public void init() {
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
        JuMeiSmsParam paramConfig = (JuMeiSmsParam) msgChannel.getParamConfig();
        this.jmSmsProperties = new JMSmsProperties();
        this.jmSmsProperties.setAppCode(paramConfig.getAppCode());
        this.jmSmsProperties.setEnable(true);
        this.jmSmsManager = new JMSmsManager(jmSmsProperties, restTemplate);
    }

    public SmsJmMsgClient(MsgChannel msgChannel) {
        super(msgChannel);
    }

    @Override
    public SmsChannelResp send(PushTaskContext context) {
        MsgParam msgParam = context.getMsgParam();
        MsgSettings msgSettings = context.getMsgSettings();

        log.debug("send msg to sms, msg: {}", JSON.toJSONString(msgSettings, JSONWriter.Feature.WriteEnumsUsingName));

        JSONObject data = new JSONObject();
        msgSettings.getTplField().values().forEach(e -> data.put(e.getKey(), e.getValue()));

        JMSmsReps reps = jmSmsManager.send(JMSmsReq.builder()
                .templateId(msgSettings.getTemplateId()).templateParam(data)
                .phoneNumbers(msgParam.getToUser()).build());
        boolean success = reps.isSuccess();
        return SmsChannelResp.builder().success(success).content(JSON.toJSONString(reps)).build();
    }
}
